package com.chenyue.cm.user.service.impl;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chenyue.cm.base.dao.LcBaseMapper;
import com.chenyue.cm.base.service.BaseServiceImpl;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.constant.Constants;
import com.chenyue.cm.common.utils.StringUtil;
import com.chenyue.cm.common.utils.StringUtils;
import com.chenyue.cm.common.vo.Page;
import com.chenyue.cm.exception.OrderNumberRule;
import com.chenyue.cm.user.client.MallGoodsServiceClient;
import com.chenyue.cm.user.dao.*;
import com.chenyue.cm.user.domain.*;
import com.chenyue.cm.user.domain.vo.*;
import com.chenyue.cm.user.service.*;
import com.chenyue.cm.utils.DateUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author chenyue-cm
 */
@Service(value = "JdOrderInfoService")
public class JdOrderInfoServiceImpl extends BaseServiceImpl<JdOrderInfo> implements JdOrderInfoService {

    private final JdOrderInfoMapper jdOrderInfoMapper;
    @Resource
    private JdOrderItemService jdOrderItemService;
    @Resource
    private JdOrderItemMapper jdOrderItemMapper;
    @Resource
    private JdGoodsSkuService jdGoodsSkuService;
    @Resource
    private JdMemberShoppingCartService memberShoppingCartService;
    @Resource
    private JdGoodsSpuService jdGoodsSpuService;
    @Resource
    private MallGoodsServiceClient goodsServiceClient;
    @Resource
    private JdMemberCouponsService memberCouponsService;
    @Resource
	private JdAppUserService appUserService;
    @Resource
	private JdMemberAddressService memberAddressService;
    @Resource
	private JdDiscountCouponService discountCouponService;
    @Resource
    private JdOrderRefundApplyMapper jdOrderRefundApplyMapper;
    @Resource
    private JdOrderLogService jdOrderLogService;
    @Resource
    private JdOrderCommentMapper jdOrderCommentMapper;
    @Resource
    private JdGoodsStockLogService goodsStockLogService;
    @Resource
    private JdMemberAddressMapper memberAddressMapper;

    public JdOrderInfoServiceImpl(@Qualifier("jdOrderInfoMapper") JdOrderInfoMapper jdOrderInfoMapper) {
        this.jdOrderInfoMapper = jdOrderInfoMapper;
    }

    @Override
    @Resource(name = "jdOrderInfoMapper")
    public void setBaseMapper(LcBaseMapper<JdOrderInfo, Serializable> baseMapper) {
        this.baseMapper = baseMapper;
    }

    @Override
    public JdOrderInfo saveGoodsOrder(GoodsJSVo goodsJSVo) {

        JdOrderInfo vo = new JdOrderInfo();
        String execute = OrderNumberRule.execute();
        //订单编号
        vo.setOrderNo(execute);
        vo.setUserId(goodsJSVo.getUserId());
        //地址ID
        vo.setAddressId(goodsJSVo.getAddressId());
        //地址详情
        vo.setAddressDetail(goodsJSVo.getAddressDetail());
        //商品dnajia
        vo.setUnitPrice(goodsJSVo.getIntegral());
        //订单金额
        vo.setOrderMoney(goodsJSVo.getTotalPrice());
        //订单备注
        vo.setRemark(goodsJSVo.getRemark());
        //订单状态
        vo.setOrderStatus(Constants.ORDER_STATUS_0);
        //获取规格信息
        vo.setSkuId(goodsJSVo.getSkuId());
        //=====================规格信息 库存-1====================//
        JdGoodsSku goodsSku = jdGoodsSkuService.getById(goodsJSVo.getSkuId());
        if (goodsSku.getSkuStock()==0){
            return null;
        }
        goodsSku.setSkuStock(goodsSku.getSkuStock()-1);
        jdGoodsSkuService.updateById(goodsSku);
        //获取商品信息
        vo.setSpuId(goodsJSVo.getSpuId());
        //下单时间
        String date = DateUtil.date().toStringDefaultTimeZone();
        vo.setCreateTime(date);
        //商品数量
        vo.setGoodsCount(goodsJSVo.getNumber());
        //商品总价
        vo.setOrderMoney(goodsJSVo.getTotalPrice());
        //商品详情
        vo.setGoodsDetail(goodsJSVo.getSpuInfo() + " + " + goodsJSVo.getSkuInfo());
        //备注信息
        if (StringUtils.isNotEmpty(goodsJSVo.getRemark())){
            vo.setRemark(goodsJSVo.getRemark());
        }
        jdOrderInfoMapper.insert(vo);
        return vo;
    }

    //@Override
    public Success saveOrderInfo(String id, String orderId, OrderVo vo) {
        String orderItemListString = JSON.toJSONString(vo.getOrderItemList());
        //【feign远程调用】--校验库存
        Success stockRes = goodsServiceClient.verifyStockInfo(orderItemListString);
        if (stockRes.getCode() != 0) {
            return stockRes;
        }
        //校验优惠券
        if (StringUtils.isNotBlank(vo.getCouponsId())) {
            Success couponsRes = memberCouponsService.checkCoupons(id, vo.getCouponsId(), orderId);
            if (couponsRes.getCode() != 0) {
                return couponsRes;
            }
        }
        //【feign远程调用】--更新库存
        Success b = goodsServiceClient.changeStockInfo(orderItemListString);
        System.out.println("更新库存结果：" + JSON.toJSONString(b));
//		getOrderInfo(userId, orderId, vo);
        //清除购物车信息
        if (StringUtils.isNotEmpty(vo.getCartIds())) {
            clearCart(vo.getCartIds());
        }
        return Success.success();
    }

    @Override
    public GoodsJSVo createOrder(HttpServletRequest request) {
        return null;
    }

    @Override
    public Success createShoppingOrder(HttpServletRequest request) {
		//根据token获取用户id
		Integer userId = appUserService.getAppUserByToken(request.getParameter("token")).getId();
		// 获取地址
		LambdaQueryWrapper<JdMemberAddress> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JdMemberAddress::getMemberId, userId);
        wrapper.eq(JdMemberAddress::getDefaultFlag, Constants.COMMON_STATUS_1);
        JdMemberAddress address = memberAddressService.getOne(wrapper);

        // 根据购物车id获取商品信息
        String cartIds = request.getParameter("cartIds");
        List<JdMemberShoppingCart> memberShoppingCartList = new ArrayList<>();
        if (StringUtils.isNotEmpty(cartIds)) {
            String[] ids = cartIds.split(",");
            for (String id : ids) {
				JdMemberShoppingCart mMemberShoppingCart = memberShoppingCartService.getById(id);
                if (mMemberShoppingCart != null) {
                    if (mMemberShoppingCart.getSkuId() == null) {
                        mMemberShoppingCart.setSkuId("");
                        mMemberShoppingCart.setSkuAttrInfo("");
                    }
                    memberShoppingCartList.add(mMemberShoppingCart);
                } else {
                    return Success.error("商品已售完");
                }
            }
        } else {
            JdMemberShoppingCartExample memberShoppingCartExample = new JdMemberShoppingCartExample();
            memberShoppingCartExample.createCriteria().andMemberIdEqualTo(userId.toString());
            // 默认时间降序
            memberShoppingCartExample.setOrderByClause("create_time DESC");
            memberShoppingCartList = memberShoppingCartService.selectByExample(memberShoppingCartExample);
        }
        //封装返回结果
        Map<String, Object> resultList = new HashMap<>();
        resultList.put("cartIds", cartIds);
        BigDecimal totalPrice = new BigDecimal(0);
        Integer num = 0;
        List<GoodsVo> goodsList = new ArrayList<>();
        if (memberShoppingCartList.size() > 0) {
            for (int i = 0; i < memberShoppingCartList.size(); i++) {
                Map<String, Object> map = JSON.parseObject(JSON.toJSONString(memberShoppingCartList.get(i)));
                String goodsid = map.get("goodsId").toString();
                JdGoodsSpu a = jdGoodsSpuService.selectByPrimaryKey(goodsid);
                map.put("goodsPic", StringUtils.isEmpty(a.getImgUrl()) ? "" : a.getImgUrl());
                map.put("goodsName", a.getGoodName());
                String skuid = map.get("skuId").toString();
                map.put("skuId", skuid);
                if (map.containsKey("skuAttrInfo")) {
                    map.put("attrInfo", map.get("skuAttrInfo").toString());
                }
                JdGoodsSku sku;
                if (StringUtils.isNotEmpty(skuid)) {
                    sku = jdGoodsSkuService.getById(skuid);
                } else {
                	LambdaQueryWrapper<JdGoodsSku> w = new LambdaQueryWrapper<>();
                    w.eq(JdGoodsSku::getGoodsId, goodsid);
                    sku = jdGoodsSkuService.getOne(w);
                }
                if (sku.getSkuStock() < Integer.valueOf(map.get("purchaseNum").toString())) {
                    return Success.error("库存不足");
                }

                map.put("goodsPrice", sku.getSkuSaleprice());
                totalPrice = totalPrice.add(sku.getSkuSaleprice().multiply(new BigDecimal(map.get("purchaseNum").toString())));
                GoodsVo goodsVo = JSON.parseObject(JSON.toJSONString(map), GoodsVo.class);
                goodsList.add(goodsVo);
                num = num + memberShoppingCartList.get(i).getPurchaseNum();
            }
        }
        resultList.put("goodList", goodsList);
        resultList.put("totalPrice", totalPrice);//总价
        Map<String, Object> map = new HashMap<>();
        map.put("member_id", userId);
        BigDecimal couponPrice = new BigDecimal(0);
        String couponId = request.getParameter("couponId");
        if (StringUtils.isNotEmpty(couponId)) {
            JdDiscountCoupon discountCoupon = discountCouponService.getById(couponId);
            couponPrice = discountCoupon.getDiscountValue();
            resultList.put("couponsId", couponId);
            resultList.put("districtMoney", couponPrice);
        } else {
            resultList.put("districtMoney", "0");
        }

        resultList.put("paymentMoney", totalPrice.subtract(couponPrice));//总价
        resultList.put("fee", "0");//运费
        resultList.put("addressId", address == null ? "" : address.getId());
        resultList.put("buyerName", address == null ? "" : address.getBuyerName());
        resultList.put("buyerPhone", address == null ? "" : address.getBuyerPhone());
        resultList.put("selectedNum", num);
        resultList.put("addressDetail", address == null ? "" : address.getProvinceName() + address.getCityName() + address.getAreaName() + address.getAddressDetail());
        GoodsJSVo vo = JSON.parseObject(JSON.toJSONString(resultList), GoodsJSVo.class);
        return Success.success(vo);
    }

    @Override
    public Page<List<OrderResultListVo>> getMemberOrderList(String id, Integer page, Integer rows, Integer orderType) {
        LambdaQueryWrapper<JdOrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JdOrderInfo::getUserId,id);
        if (orderType != 0){
            wrapper.eq(JdOrderInfo::getOrderStatus,orderType);
        }
        wrapper.ne(JdOrderInfo::getOrderStatus,11);
        int total = jdOrderInfoMapper.selectCount(wrapper);
        Page<List<OrderResultListVo>> result = new Page<>(page, rows, total);
        wrapper.last(result.convertPage());
        List<JdOrderInfo> jdOrderInfos = jdOrderInfoMapper.selectList(wrapper);
        List<OrderResultListVo> voList = toNewVo(jdOrderInfos);
        result.setContent(voList);
        return result;
    }


    public List<OrderResultListVo> toNewVo(List<JdOrderInfo> jdOrderInfos)
    {
        List<OrderResultListVo> list = new ArrayList<>();
        for (JdOrderInfo info:jdOrderInfos) {
                JdOrderInfo orderInfo = jdOrderInfoMapper.selectById(info.getId());
            OrderResultListVo resultVo = new OrderResultListVo();
            resultVo.setId(orderInfo.getId());
            //订单编号
            resultVo.setOrderId(orderInfo.getOrderNo());
            //商品名称
            JdGoodsSpu spu = jdGoodsSpuService.getById(orderInfo.getSpuId());
            resultVo.setOrderItem(spu.getGoodName());
            resultVo.setOrderImage(spu.getImgUrl());
            JdGoodsSku sku = jdGoodsSkuService.getById(orderInfo.getSkuId());
            resultVo.setOrderSku(sku.getAttrInfo());
            resultVo.setOrderStatus(orderInfo.getOrderStatus());
            resultVo.setOrderMoney(orderInfo.getUnitPrice());
            resultVo.setPaymentMoney(orderInfo.getOrderMoney());
            resultVo.setTotalNum(orderInfo.getGoodsCount());
            resultVo.setTime(orderInfo.getCreateTime());
            list.add(resultVo);
        }
        return list;
    }



    @Override
    public OrderDetailVo getOrderDetail(JdAppUser user,String id) {
        //根据订单id获取订单信息
        JdOrderInfo orderInfo = jdOrderInfoMapper.selectById(id);
        OrderDetailVo detailVo = new OrderDetailVo();
        //订单ID
        detailVo.setOrderId(orderInfo.getId());
        //订单编号
        detailVo.setOrderNo(orderInfo.getOrderNo());
        //商品数量
        detailVo.setGoodsCount(orderInfo.getGoodsCount());
        //单价
        detailVo.setOrderMoney(orderInfo.getOrderMoney()/orderInfo.getGoodsCount());
        //总价
        detailVo.setPaymentMoney(orderInfo.getOrderMoney());
        //兑换时间
        detailVo.setPayTime(orderInfo.getCreateTime());
        //发货时间
        detailVo.setDeliveryTime(orderInfo.getDeliveryTime());
        //收货时间
        detailVo.setCompleteTime(orderInfo.getCompleteTime());
        //商品信息
        JdGoodsSpu spu = jdGoodsSpuService.getById(orderInfo.getSpuId());
        detailVo.setImage(spu.getImgUrl());
        detailVo.setItemInfo(spu.getGoodName());
        JdGoodsSku sku = jdGoodsSkuService.getById(orderInfo.getSkuId());
        detailVo.setSkuInfo(sku.getAttrInfo());
        detailVo.setGoodsCount(orderInfo.getGoodsCount());
        //收货人信息
        JdMemberAddress addressOne = memberAddressService.getOne(new LambdaQueryWrapper<JdMemberAddress>().eq(JdMemberAddress::getMemberId, user.getId()).eq(JdMemberAddress::getDefaultFlag,1));
        detailVo.setBuyerName(addressOne.getBuyerName());
        detailVo.setBuyerPhone(addressOne.getBuyerPhone());
        detailVo.setAddressDetail(orderInfo.getAddressDetail());
        //备注
        detailVo.setRemark(orderInfo.getRemark());
        //订单状态
        detailVo.setStatus(orderInfo.getOrderStatus());
        //物流
        detailVo.setLogisticsNum(orderInfo.getLogisticsId());
        detailVo.setLogisticsName(orderInfo.getLogisticsFee());
        return detailVo;
    }

    @Override
    public List<OrderItemDetailVo> getOrderItemList(String orderId, String skuId, String keyWords, String flag) {
        List<OrderItemDetailVo> result = new ArrayList<>();

        List<JdOrderItem> orderItemList = getOrderItemListByOrderId(orderId, skuId, keyWords,flag);
        String imgUrl = null;
        for (JdOrderItem orderItem : orderItemList) {
            //【feign远程调用】--获取SPU详情
            Success e = goodsServiceClient.getSpuDetailById(orderItem.getGoodsId());
            Map<String, Object> spuDetailMap = JSON.parseObject(JSON.toJSONString(e.getResult()));
            imgUrl = spuDetailMap.get("imgUrl").toString();
            OrderItemDetailVo vo = new OrderItemDetailVo();
            vo.setGoodId(orderItem.getGoodsId()); //商品id
            vo.setSkuNum(orderItem.getSkuNum().toString());  //数量
            //规格id
            vo.setSkuId(orderItem.getSkuId());
            vo.setGoodName(orderItem.getGoodsName()); //商品名称
            vo.setGoodImg(imgUrl);   //商品图片
            vo.setTotalPrice(orderItem.getTotalPrice().divide(new BigDecimal(orderItem.getSkuNum()), 2, BigDecimal.ROUND_HALF_UP).toString());   //原价
            vo.setFeeMoney(orderItem.getFeeMoney() == null ? "0" : orderItem.getFeeMoney().toString());  //优惠金额
            vo.setPayMoney(orderItem.getPaymentMoney().toString());  //实付金额
            vo.setAttrInfo(orderItem.getSkuDetail());  //规格信息
            vo.setStatus(orderItem.getOrderItemStatus());
            result.add(vo);
        }
        return result;
    }

    @Override
    public List<JdOrderItem> getOrderItemListByOrderId(String orderId, String skuId, String keyWords, String flag) {
        JdOrderInfo orderInfo = jdOrderInfoMapper.selectById(orderId);
        LambdaQueryWrapper<JdOrderItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JdOrderItem::getOrderId, orderId);
        if (skuId != null) {
            wrapper.eq(JdOrderItem::getSkuId, skuId);
        }
        if (StringUtils.isNotEmpty(keyWords)) {
            wrapper.like(JdOrderItem::getGoodsId, keyWords);
        }
        if(StringUtils.isNotEmpty(flag)&&flag.equals("3")){
            wrapper.ne(JdOrderItem::getOrderItemStatus, Constants.ORDER_STATUS_2);
        }
        List<JdOrderItem> orderItemList = jdOrderItemMapper.selectList(wrapper);
        if (orderId.equals(keyWords)) {
            LambdaQueryWrapper<JdOrderItem> w = new LambdaQueryWrapper<>();
            w.eq(JdOrderItem::getOrderId, orderId);
            orderItemList = jdOrderItemMapper.selectList(w);
        }
        return orderItemList;
    }

    @Override
    public Success cancellationOrder(String id, String orderId) {
        //修改订单状态
        JdOrderInfo order = this.jdOrderInfoMapper.selectById(orderId);
        if (null != order) {
            order.setOrderStatus(Constants.ORDER_STATUS_11);
            jdOrderInfoMapper.updateById(order);
            //sku商品数量 返值
                //商品+商品规格
            JdGoodsSku goodsSku = jdGoodsSkuService.getById(order.getSkuId());
            if (goodsSku.getSkuStock()>=0){
                goodsSku.setSkuStock(goodsSku.getSkuStock() + order.getGoodsCount());
            }
            jdGoodsSkuService.updateById(goodsSku);
            //增加该商品规格的库存
            JdGoodsStockLog mGoodsStockLog = new JdGoodsStockLog();
            mGoodsStockLog.setId(StringUtil.getUuid());
            mGoodsStockLog.setSkuId(order.getSkuId());
            mGoodsStockLog.setLogType(Constants.STOCK_LOG_TYPE_4);
            mGoodsStockLog.setOriginalNum(goodsSku.getSkuStock());
            mGoodsStockLog.setChangeNum(order.getGoodsCount());
            mGoodsStockLog.setResultNum(goodsSku.getSkuStock() + order.getGoodsCount());
            mGoodsStockLog.setCreateTime(DateUtils.getCurrentTime());
            this.goodsStockLogService.save(mGoodsStockLog);

            }
            /*************************************4.记录订单日志 ****************************************/
            JdOrderLog orderLog = new JdOrderLog();
            //订单id
            orderLog.setOrderId(orderId);
            //用户id
            orderLog.setMemberId(id);
            orderLog.setCreateUser(id);
            orderLog.setCreateTime(DateUtils.getCurrentTime());
            //订单日志类型
            orderLog.setLogType(Constants.ORDER_LOG_TYPE_3);
            jdOrderLogService.save(orderLog);
            return Success.success();
    }

    @Override
    public Success saveOrderComment(HttpServletRequest request, JdAppUser appUser) {
        try {
            //搜索订单信息
            JdOrderInfo mOrderInfo = jdOrderInfoMapper.selectById(request.getParameter("orderId"));
            if (mOrderInfo == null) {
                return Success.error("订单不存在");
            }
            if (!mOrderInfo.getOrderStatus().equals(Constants.ORDER_STATUS_9)) {
                return Success.error("订单未完成,无法添加评论");
            }
            String orderId = request.getParameter("orderId");
            String commentArry = request.getParameter("commentArry");
            JSONArray array = JSON.parseArray(commentArry);
            if (array != null && array.size() > 0) {
                for (int i = 0; i < array.size(); i++) {
                    JSONObject job = array.getJSONObject(i);
                    String goodsId = job.getString("goodsId");
                    String content = job.getString("content");
                    String skuId = job.getString("skuId");
                    String img = job.getString("img");
                    //搜索下单商品信息

                    JdOrderItem mOrderItem = new JdOrderItem();
                    mOrderItem.setOrderId(orderId);
                    mOrderItem.setGoodsId(goodsId);
                    mOrderItem.setSkuId(skuId);
                    mOrderItem = jdOrderItemService.getById(mOrderItem);

                    //组装评论信息
                    JdOrderComment comment = new JdOrderComment();
                    comment.setGoodsId(goodsId);
                    comment.setGoodsName(jdGoodsSpuService.getById(goodsId).getGoodName());
                    comment.setMemberId(appUser.getId().toString());
                    comment.setMemberName(appUser.getUserName());
                    comment.setMemberPic(appUser.getMobile());
                    comment.setOrderId(orderId);
                    comment.setMemberPic(appUser.getMobile());
                    comment.setCommentContent(content);
                    comment.setSkuDetail(mOrderItem.getSkuDetail());
                    comment.setSkuId(mOrderItem.getSkuId());
                    comment.setCommentPics(img);
                    comment.setCreateTime(DateUtils.getCurrentTime());
                    comment.setShowFlag(1);
                    jdOrderCommentMapper.insert(comment);
//                    mOrderItem.setOrderItemStatus(Constants.ORDER_STATUS_10);
//                    mOrderItenMapper.updateById(mOrderItem);
                }
            }
            mOrderInfo.setOrderStatus(Constants.ORDER_STATUS_10);
            jdOrderInfoMapper.updateById(mOrderInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Success.error("添加评论发生异常");
        }
        return Success.success("添加成功");
    }

    @Override
    public Success getSumMoney(List<JdOrderItem> orderItem) {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        BigDecimal totalPrice = new BigDecimal(0);
        for (JdOrderItem item : orderItem) {
            Map<String, Object> goodsMap = new HashMap<>();
            JdGoodsSpu goodsSpu = jdGoodsSpuService.getById(item.getGoodsId());
            goodsMap.put("goodsName", goodsSpu.getGoodName());
            goodsMap.put("goodsImg", goodsSpu.getImgUrl());
            JdGoodsSku goodsSku = jdGoodsSkuService.getById(item.getSkuId());
            goodsMap.put("saleprice", goodsSku.getSkuSaleprice());
            goodsMap.put("skuNum", item.getSkuNum());
            goodsMap.put("attrInfo", item.getSkuDetail());
            goodsMap.put("skuId", item.getSkuId());
            list.add(goodsMap);
            totalPrice = totalPrice.add(item.getPaymentMoney());
        }
        map.put("goodsList", list);
        map.put("totalPrice", totalPrice);
        return Success.success(map);
    }

    @Override
    public Success refundApply(String id, HttpServletRequest request) {
        //搜索订单信息
        try {
            String orderId = request.getParameter("orderId");
            JdOrderInfo mOrderInfo = jdOrderInfoMapper.selectById(orderId);
            if (mOrderInfo == null) {
                return Success.error("订单不存在");
            }
            if (!mOrderInfo.getOrderStatus().equals(Constants.ORDER_STATUS_1) && !mOrderInfo.getOrderStatus().equals(Constants.ORDER_STATUS_2) && !mOrderInfo.getOrderStatus().equals(Constants.ORDER_STATUS_3)) {
                return Success.error("订单无法申请退款");
            }

            String goodsId = request.getParameter("goodsId");
            String skuId = request.getParameter("skuId");
            if (StringUtils.isNotEmpty(goodsId)) {
                String[] ids = goodsId.split(",");
                for (String did : ids) {
                    JdOrderRefundApply mOrderRefundApply = new JdOrderRefundApply();
                    mOrderRefundApply.setOrderId(orderId);
                    mOrderRefundApply.setGoodsId(goodsId);
                    mOrderRefundApply.setSkuId(skuId);
                    mOrderRefundApply = jdOrderRefundApplyMapper.selectById(mOrderRefundApply);

                    JdOrderItemExample itemExample = new JdOrderItemExample();
                    itemExample.createCriteria().andGoodsIdEqualTo(id).andOrderIdEqualTo(orderId).andSkuIdEqualTo(skuId);
                    JdOrderItem item = jdOrderItemService.selectByExample(itemExample).get(0);

                    if (mOrderRefundApply != null) {
                        mOrderRefundApply.setState(Constants.ORDER_STATUS_1);
                        mOrderRefundApply.setRefundType(request.getParameter("refundType"));
                        String refundType = request.getParameter("refundReasonType");
                        mOrderRefundApply.setRefundReasonType(refundType);
                        mOrderRefundApply.setRefundPics(request.getParameter("refundPics"));
                        mOrderRefundApply.setContent(request.getParameter("content"));
                        mOrderRefundApply.setEt(DateUtils.getCurrentTime());
                        mOrderRefundApply.setEb(did);
                        jdOrderRefundApplyMapper.updateById(mOrderRefundApply);
                    } else {
                        JdOrderRefundApply apply = new JdOrderRefundApply();
                        apply.setId(java.util.UUID.randomUUID().toString().replace("-", ""));
                        apply.setOrderId(mOrderInfo.getId());
                        apply.setMemberId(did);
                        apply.setRefundType(request.getParameter("refundType"));
                        apply.setGoodsId(did);
                        JdGoodsSpu spu = jdGoodsSpuService.getById(did);
                        if (spu == null) {
                            continue;
                        }
                        apply.setGoodsName(spu.getGoodName());

                        if (item == null) {
                            continue;
                        }
                        apply.setSkuId(item.getSkuId());
                        apply.setSkuDetail(item.getSkuDetail());
                        //受理状态(1-提交申请 2-同意退款   3-退款成功)
                        apply.setState(Constants.ORDER_STATUS_1);
                        apply.setCt(DateUtils.getCurrentTime());
                        apply.setCb(did);
                        apply.setEt(DateUtils.getCurrentTime());
                        apply.setEb(did);
                        String refundType = request.getParameter("refundReasonType");
                        apply.setRefundReasonType(refundType);
                        apply.setRefundPics(request.getParameter("refundPics"));
                        apply.setContent(request.getParameter("content"));
                        apply.setRefundMoney(item.getPaymentMoney());
                        //保存退款记录
                        jdOrderRefundApplyMapper.insert(apply);
                    }
                    if (request.getParameter("refundType").equals("1")) {
                        item.setOrderItemStatus(Constants.ORDER_STATUS_1);
                    } else if (request.getParameter("refundType").equals("2")) {
                        item.setOrderItemStatus(Constants.ORDER_STATUS_4);
                    }
                    jdOrderItemService.updateById(item);
                }
            }
//            //修改订单状态为申请退款
//            mOrderInfo.setOrderStatus(Constants.ORDER_STATUS_4);
//            this.updateById(mOrderInfo);


        } catch (Exception e) {
            e.printStackTrace();
            return Success.error("申请退款失败");
        }
        return Success.success("申请退款成功");
    }

    @Override
    public OrderDetailVo getorderlist(String orderId) {
        //根据订单id获取订单信息
        JdOrderInfo orderInfo = jdOrderInfoMapper.selectById(orderId);
        OrderDetailVo detailVo = new OrderDetailVo();
        //订单ID
        detailVo.setOrderId(orderInfo.getId());
        //订单编号
        detailVo.setOrderNo(orderInfo.getOrderNo());
        //单价
        detailVo.setOrderMoney(orderInfo.getOrderMoney());
        detailVo.setGoodsCount(orderInfo.getGoodsCount());
        //总价
        detailVo.setPaymentMoney(orderInfo.getGoodsCount()*orderInfo.getOrderMoney());
        //兑换时间
        detailVo.setPayTime(orderInfo.getCreateTime());
        //发货时间
        detailVo.setDeliveryTime(orderInfo.getDeliveryTime());
        //收货时间
        detailVo.setCompleteTime(orderInfo.getCompleteTime());
        //商品信息
        JdGoodsSpu spu = jdGoodsSpuService.getById(orderInfo.getSpuId());
        detailVo.setImage(spu.getImgUrl());
        detailVo.setItemInfo(spu.getGoodName());
        JdGoodsSku sku = jdGoodsSkuService.getById(orderInfo.getSkuId());
        detailVo.setSkuInfo(sku.getAttrInfo());
        JdAppUser user = appUserService.getById(orderInfo.getUserId());
        detailVo.setBuyerName(user.getUserName());
        detailVo.setBuyerPhone(user.getMobile());
        detailVo.setAddressDetail(orderInfo.getAddressDetail());
        //备注
        detailVo.setRemark(orderInfo.getRemark());
        //订单状态
        detailVo.setStatus(orderInfo.getOrderStatus());
        //物流
        detailVo.setLogisticsNum(orderInfo.getLogisticsId());
        detailVo.setLogisticsName(orderInfo.getLogisticsFee());
        return detailVo;
    }

    /**
     * 清除购物车信息
     *
     * @param cartIds
     */
    private void clearCart(String cartIds) {
        String[] ids = cartIds.split(",");
        for (String id : ids) {
            JdMemberShoppingCart cart = memberShoppingCartService.selectByPrimaryKey(id);
            if (cart == null) {
                continue;
            }
            memberShoppingCartService.deleteByPrimaryKey(id);
        }
    }

    /**
     * 判断订单是否评论
     *
     * @param orderId
     * @return
     */
    boolean isComment(String orderId) {
        LambdaQueryWrapper<JdOrderComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JdOrderComment::getOrderId, orderId);
        Integer count = jdOrderCommentMapper.selectCount(wrapper);
        if (count > 0) {
            return true;
        }
        return false;
    }
}
